package com.example.demo.netty.chat_room.client;

import com.example.demo.netty.chat_room.domain.MessageProtocol;
import com.example.demo.netty.chat_room.util.MessageDecoder;
import com.example.demo.netty.chat_room.util.MessageEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Scanner;

public class ChatClient {
    public static void main(String[] args) {
        // 基础配置
        EventLoopGroup workGroup =new NioEventLoopGroup(10);

        try {
            Bootstrap bootstrap= new Bootstrap();
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
//                                    .addLast(new StringEncoder())
//                                    .addLast(new StringDecoder())
                                    .addLast(new MessageEncoder())
                                    .addLast(new MessageDecoder())
                                    .addLast(new ClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect("127.0.0.1", 7000).sync();
            Scanner scanner = new Scanner(System.in);
            // 阻塞写入
            while(scanner.hasNext()){
                String str =scanner.nextLine();
                // 发送消息
                sendData(str, future.channel());
                if("断开连接".equals(str)){
                    System.out.println("下线！");
                    break;
                }
            }
            // 这个只是用来阻塞的,上面的while已经阻塞了,所以就不用它了
            // future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            workGroup.shutdownGracefully();
        }


    }

    public static void sendData(String str,Channel channel){
        byte[] bytes = str.getBytes();
        channel.writeAndFlush(new MessageProtocol(bytes.length, bytes));
    }


}
